package br.ufpe.cin.mac.middleware.components.concrete;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import br.ufpe.cin.mac.middleware.components.ConcreteComponent;
import br.ufpe.cin.mac.util.Message;

public class Manager extends ConcreteComponent implements ManagerMBean {

	// private final byte NEW_MESSAGE = 0;

	// private final byte SEND_MESSAGE = 1;

	// private final byte RETURN_MESSAGE = 2;

	private Map<Integer, Message> queue, buffer;

	// private long seq;

	public Manager() {
		super(Manager.class.getName());
		queue = Collections.synchronizedMap(new HashMap<Integer, Message>());
	}

	/***************************************************************************
	 * ************************************************************
	 * ******************** INTERNAL METHODS ********************** *
	 * ************************************************************
	 */

	protected void msgManager(Message msg) {
		List<String> ops = msg.readOperations();
		Iterator<String> it = ops.iterator();
		while (it.hasNext()) {
			String op = it.next();

			if (op.equals("sendRequest"))
				sendRequest(msg);

			else if (op.equals("sendResponse"))
				sendResponse(msg);

			else
				System.err.println(op + " Not operation available");
		}
	}

	private void sendRequest(Message msg) {
		queue.put(msg.hashCode(), msg);
		sendNotification(msg, "invU");
	}

	private void sendResponse(Message msg) {
		buffer.put(msg.hashCode(), msg);
		queue.remove(msg);
		sendNotification(msg, "terP");
	}
}
